package hall

import (
	"fmt"
	"time"
	"webgame/internal/model/entity/hall"

	"github.com/topfreegames/pitaya/v2/component"
	"github.com/topfreegames/pitaya/v2/logger"
)

// 接收进程 收到排队通知 调用loginManager登录
type RemoteLoginThreadPool struct {
	loginChan chan *hall.LoginInfo
	workers   []component.LogicThread
}

func (r *RemoteLoginThreadPool) Init() {
	sleep := 100
	workerSize := 1
	run := func() {
		select {
		case info := <-r.loginChan:
			//执行登录
			fmt.Println("RemoteLoginThreadPool Run:", info)
			LoginManager.DoLogin(info.Ctx, info)
		default:
			time.Sleep(time.Duration(sleep) * time.Millisecond)
		}
	}

	for i := 0; i < workerSize; i++ {
		worker := component.LogicThread{
			DieChan: make(chan struct{}, 1),
			Run:     run,
			Name:    fmt.Sprintf("[RemoteLoginWorker-%d]", i),
		}

		worker.Run = run
		r.workers = append(r.workers, worker)
		worker.Init()
	}

	logger.Log.Infof("启动远程登录线程池，共启动协程数：%d", workerSize)

}

func (r *RemoteLoginThreadPool) Shutdown() {
	for _, worker := range r.workers {
		worker.Shutdown()
	}
	close(r.loginChan)
}

func (r *RemoteLoginThreadPool) doRemoteLogin(loginInfo *hall.LoginInfo) bool {
	if loginInfo == nil {
		return false
	}

	r.loginChan <- loginInfo
	return true
}

// 获取当前登录队列的登录人数
func (r *RemoteLoginThreadPool) getCurrentLoginInfoNum() int {
	return len(r.loginChan)
}
